import 'package:easy_refresh/easy_refresh.dart';
import 'package:flustars/flustars.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bugly/flutter_bugly.dart';
import 'package:flutter_keyboard_visibility/flutter_keyboard_visibility.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:zrjz/comm/constants/app_constant.dart';
import 'package:zrjz/comm/widget/dialog/custom_error_widget.dart';
import 'package:zrjz/comm/widget/dialog/custom_failure_widget.dart';
import 'package:zrjz/comm/widget/dialog/custom_success_widget.dart';
import 'package:get/get.dart';
import 'package:zrjz/app_binding.dart';
import 'package:zrjz/comm/utils/log_utils.dart';
import 'package:zrjz/comm/widget/dialog/custom_loading_widget.dart';
import 'package:zrjz/comm/widget/dialog/custom_toast_widget.dart';
import 'package:zrjz/local/language/translation_service.dart';
import 'package:zrjz/local/theme/theme_config.dart';
import 'package:zrjz/router/getx_router_observer.dart';
import 'package:zrjz/router/page_router.dart';

void main() {
  //运行App
  FlutterBugly.postCatchedException(() async {
    //FT框架初始化
    WidgetsFlutterBinding.ensureInitialized();

    //初始化SP
    await SpUtil.getInstance();

    //Log框架初始化
    Log.init();

    //指定页面的展示方向为哪一种，常用的三种屏幕方向
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp,
      DeviceOrientation.landscapeLeft,
      DeviceOrientation.landscapeRight,
    ]);

    runApp(MyApp());
  });

  //处理显示区域
  SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual, overlays: [SystemUiOverlay.top, SystemUiOverlay.bottom]);
}

class MyApp extends StatelessWidget {
  MyApp({Key? key}) : super(key: key) {
    /// 全局设置 EasyRefresh 的样式
    EasyRefresh.defaultHeaderBuilder = () => ClassicHeader(
          dragText: '下拉刷新'.tr,
          armedText: '释放刷新'.tr,
          readyText: '刷新中...'.tr,
          processingText: '刷新中...'.tr,
          processedText: '成功'.tr,
          noMoreText: '没有更多数据'.tr,
          failedText: '失败'.tr,
          messageText: '最近更新于 %T'.tr,
        );
    EasyRefresh.defaultFooterBuilder = () => ClassicFooter(
          dragText: '上拉加载更多'.tr,
          armedText: '释放刷新'.tr,
          readyText: '加载中...'.tr,
          processingText: '加载中...'.tr,
          processedText: '成功'.tr,
          noMoreText: '没有更多数据'.tr,
          failedText: '成功'.tr,
          showMessage: false,
          triggerOffset: 50,
          iconDimension: 22,
        );

    /// SmartDialog 配置
    SmartDialog.config
      ..custom = SmartConfigCustom(
        maskColor: Colors.black.withOpacity(0.35),
        useAnimation: true,
      )
      ..attach = SmartConfigAttach(
        animationType: SmartAnimationType.scale,
        usePenetrate: false,
      )
      ..loading = SmartConfigLoading(
        backDismiss: true,
        clickMaskDismiss: true,
      )
      ..toast = SmartConfigToast(
        intervalTime: const Duration(milliseconds: 100),
        displayTime: const Duration(milliseconds: 2000),
      );
  }

  @override
  Widget build(BuildContext context) {
    int? darkModel = SpUtil.getInt(AppConstant.storagedarkmodel, defValue: 0);
    if (GetPlatform.isAndroid) {
      //根据SP存入的暗色模式，指定全局页面的状态栏，导航栏等设置
      switch (darkModel) {
        case 1:
          Log.d("main.dart - 指定亮色模式");
          SystemChrome.setSystemUIOverlayStyle(ThemeConfig.systemUiOverlayStyleLightThemeBlack);
          break;
        case 2:
          Log.d("main.dart - 指定暗色模式");
          SystemChrome.setSystemUIOverlayStyle(ThemeConfig.systemUiOverlayStyleDarkTheme);
          break;
        default:
          Brightness currentBrightness = MediaQuery.of(context).platformBrightness;
          if (currentBrightness == Brightness.dark) {
            Log.d("main.dart - 跟随系统模式-暗色模式");
            SystemChrome.setSystemUIOverlayStyle(ThemeConfig.systemUiOverlayStyleDarkTheme);
          } else {
            Log.d("main.dart - 跟随系统模式-亮色模式");
            SystemChrome.setSystemUIOverlayStyle(ThemeConfig.systemUiOverlayStyleLightThemeBlack);
          }
          break;
      }
    }

    //路由管理，状态管理，依赖管理一切都始于GetMaterialApp
    return KeyboardVisibilityBuilder(builder: (context, isKeyboardVisible) {

      return KeyboardDismissOnTap(
        dismissOnCapturedTaps: true,
        child: GetMaterialApp(
          //顶部是否展示Debug图标
          debugShowCheckedModeBanner: true,
          //是否展示Log
          enableLog: true,
          //默认路由与路由表的加载
          initialRoute: RouterPath.SPLASH,
          getPages: PageRouter.routes,
          //对原生导航的兼容；SmartDialog路由配置生命周期处理
          navigatorObservers: [GetXRouterObserver(), FlutterSmartDialog.observer, routeObserver],
          //默认页面动画
          defaultTransition: Transition.rightToLeft,
          //异步依赖注入ApiService ApiRepository等对象
          initialBinding: AppBinding(),
          smartManagement: SmartManagement.keepFactory,
          //网页Title显示
          title: 'FlutterRoom'.tr,
          //样式相关
          theme: ThemeConfig.lightTheme,
          darkTheme: ThemeConfig.darkTheme,
          themeMode: darkModel == 1
              ? ThemeMode.light
              : darkModel == 2
                  ? ThemeMode.dark
                  : ThemeMode.system,
          //本地化相关
          locale: TranslationService.locale,
          fallbackLocale: TranslationService.fallbackLocale,
          localizationsDelegates: const [
            GlobalMaterialLocalizations.delegate,
            GlobalWidgetsLocalizations.delegate,
            GlobalCupertinoLocalizations.delegate,
          ],
          supportedLocales: const [
            Locale('zh', 'CH'),
            Locale('en', 'US'),
          ],
          translations: TranslationService(),
          //SmartDialog初始化默认Loading与Toast
          builder: FlutterSmartDialog.init(
            toastBuilder: (String msg) {
              return CustomToastWidget(msg: msg);
            },
            loadingBuilder: (String msg) {
              return CustomLoadingWidget(msg: msg == 'loading...' ? '加载中...'.tr : msg);
            },
            notifyStyle: FlutterSmartNotifyStyle(
              successBuilder: (String msg) => CustomSuccessWidget(msg: msg),
              failureBuilder: (String msg) => CustomFailureWidget(msg: msg),
              errorBuilder: (String msg) => CustomErrorWidget(msg: msg),
              alertBuilder: (String msg) => CustomErrorWidget(msg: msg),
              warningBuilder: (String msg) => CustomErrorWidget(msg: msg),
            ),
          ),
        ),
      );
    });
  }
}
